#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <pthread.h>
#include <getopt.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/resource.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/stat.h>

#include "sqlite.h"
#include "logger.h"
#include "pack_data.h"

#define LOG_LEVEL_ERROR   0  
#define LOG_LEVEL_WARN    1  
#define LOG_LEVEL_INFO    2  
#define LOG_LEVEL_DEBUG   3

//#define log_level        log_error
#define MAX_EVENTS 		1024			/* 最大监听事件数 */
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
void signal_handler(int sig);

volatile sig_atomic_t running = 1;

int print_usage(char *progname);
int set_socket_rlimit(void); 
int socket_server_init(char *listen_ip, int listen_port);
//volatile int serv_port __attribute__((used)) = 0;

int main(int argc, char **argv)
{
	int 				 listen_fd = -1;								/* socket描述符 */
	int			         conn_fd = -1;									/* accept函数返回值 */
	int 				 serv_port = -1;									/* 监听端口号 */
	int 				 daemon_run = 0;								/* 后台运行标志 */
	char 				*progname = NULL;								/* 文件名 */
	int  				 opt = 0;										/* 参数解析函数getopt_long返回值 */
//	int 				 rv = -1;										/* 函数返回值 */
	char 				 buf[128];										/* 接收数据缓冲区 */
	int 				 epoll_rv = -1;									/* epoll函数返回值 */
	struct epoll_event 	 event;											/* epoll事件 */
	struct epoll_event 	 event_array[MAX_EVENTS];						/* epoll事件数组 */
	int 				 events;										/* epoll事件数 */
	packet_t			*pack = NULL;	/* 打包函数结构体 */
	char  				*log_filename = "server.log";					/* 日志文件名 */
	int			         user_log_level = LOG_LEVEL_INFO;
	int  				 log_size = 1024;
	int                  log_lock = 1;

	struct option 		 long_options[] =								/* 解析的参数结构体 */
	{
		{"daemon", no_argument, NULL, 'b'},
		{"port", required_argument, NULL, 'p'},
		{"user_log-level", required_argument, NULL, 'l'},
		{"help", no_argument, NULL, 'h'},
		{NULL, 0, NULL, 0}
	};

	
    //signal(SIGINT, signal_handler);
   // signal(SIGTERM, signal_handler);

	progname = basename(argv[0]);	/* 文件名 */
	/*  Parser the command line parameters */
	while ((opt = getopt_long(argc, argv, "bp:l:h",long_options,NULL))!= -1 )
	{
		printf("[DEBUG] opt=%c (%d), optarg=%s\n", opt, opt, optarg ? optarg : "NULL");
		switch(opt)
		{
			case 'b':
				daemon_run=1;					/* 是否后台运行 */
				break;
			case 'p':
				serv_port = atoi(optarg);		/* 监听的端口号 */
				
				 printf("DEBUG: Using port %d\n", serv_port); // 调试输出
				
				printf("运行到port\n");
				break;

			case 'l':
            	user_log_level=atoi(optarg);
           		if(user_log_level<LOG_LEVEL_ERROR||user_log_level>LOG_LEVEL_DEBUG)
				{
               		fprintf(stderr,"Loglevelmustbe0-3\n");
               		return EXIT_FAILURE;
           		}
           		printf("Loglevel setto: %d\n",user_log_level);
           		break;

			case 'h': 
				printf("帮助信息\n");
				print_usage(progname);			/* 说明信息 */
				return EXIT_SUCCESS;
				break;
#if 0
			 default:
				printf("zzzzzzzzzzzzzzzzzz\n");
                print_usage(progname);
                return EXIT_FAILURE;
				break;
#endif
		 }
	 }
      
		printf("运行到这3\n");
        if (serv_port == 0)
       	{
    		fprintf(stderr, "Error: Port must be specified with -p\n");
    		print_usage(progname);
    		return EXIT_FAILURE;
		}

		printf("运行到这\n");

/*	printf("DEBUG: Port validation - port=%d\n", serv_port);// 添加调试行
	if (serv_port <= 0 || serv_port > 65535) 
	{  // 正确检查方式
    		fprintf(stderr, "Error: Invalid port %d (must be 1-65535)\n", serv_port);
    		print_usage(argv[0]);
    		return EXIT_FAILURE;
	}*/
	

	 /* 分配packet内存 */
        pack = (packet_t *)malloc(sizeof(packet_t));
        if (!pack)
       	{
              fprintf(stderr, "malloc packet_t failed: %s\n", strerror(errno));
              return EXIT_FAILURE;
        }
		log_open(log_filename, user_log_level, log_size , log_lock);	/* 初始化日志：设置日志文件名和记录日志级别 */
	

	/* 设置最大文件描述符数 */
         if (set_socket_rlimit() < 0)
	 	 {
               log_error("set_socket_rlimit failed");
              goto CleanUp;
          }
		  printf("程序已启动，准备初始化日志\n");  // 确认程序运行到此处
		  log_debug("调试日志测试");  // 测试日志系统是否工作
		  if( (listen_fd = socket_server_init(NULL, serv_port)) < 0 )
		  {	/* 初始化socketi，监听指定的端口号 */
				printf("[%s: ERROR: %s server listen on port %d failure]\n",   __FILE__, argv[0], serv_port);
				goto CleanUp;
			}
		  printf("监听成功\n");

			if( daemon_run )
			{	/* 判断是否后台运行 */
				printf("Running as daemon\n");
				daemon(0, 0);
			}
			printf("fge\n");
			if( (epoll_rv = epoll_create(MAX_EVENTS)) < 0 )
			{	/* 创建epoll监听队列 */
				printf("[%s: epoll_create() failure: %s]\n",   __FILE__, strerror(errno));
				return -3;
			}
			event.events = EPOLLIN|EPOLLET;	/*边缘触发  */ //仅在fd状态变化时触发一次（如新数据到达），需一次性处理完所有数据。			
			event.data.fd = listen_fd;		

			if( epoll_ctl(epoll_rv, EPOLL_CTL_ADD, listen_fd, &event) < 0)// 将sockfd添加到epoll实例中
			{	/* 创建，增加，监听的文件描述符， */
				printf("[%s: epoll add listen socket failure: %s]\n",   __FILE__, strerror(errno));
				goto CleanUp;
			}
			printf("3\n");
	  		/* 主事件循环 */
   	 		while (running)
	 		{
        		events = epoll_wait(epoll_rv, event_array, MAX_EVENTS, -1);
        		if (events < 0)
	       		{
            		if (errno == EINTR) continue;  /* 被信号中断 */
            		log_error("epoll_wait failed: %s", strerror(errno));
            		break;
        		}

        		for (int i = 0; i < events; i++)
	       		{
            		/* 处理错误事件 */
            		if (event_array[i].events & (EPOLLERR | EPOLLHUP))
		       		{
                		log_warn("epoll error on fd %d", event_array[i].data.fd);
                		close(event_array[i].data.fd);
                		continue;
            		}

            		/* 新连接到达 */
            		if (event_array[i].data.fd == listen_fd)
	    			{
                		while ((conn_fd = accept(listen_fd, NULL, NULL)) > 0)
	       			{
                    			/* 设置新连接为非阻塞 */
                    			int flags = fcntl(conn_fd, F_GETFL, 0);
                    			fcntl(conn_fd, F_SETFL, flags | O_NONBLOCK);

                    			event.events = EPOLLIN | EPOLLET;
                    			event.data.fd = conn_fd;
                    
					if (epoll_ctl(epoll_rv, EPOLL_CTL_ADD, conn_fd, &event) < 0)
		    			{
                        			log_error("epoll_ctl add client fd failed: %s", strerror(errno));
                        			close(conn_fd);
                        			continue;
                    			}
                    			log_info("New client connected: fd=%d", conn_fd);
                		   }
                		   if (conn_fd < 0 && errno != EAGAIN && errno != EWOULDBLOCK)
	       			   {
                    			log_error("accept failed: %s", strerror(errno));
                		   }
				   printf("fanda\n");
                		   continue;
            		}

            	/* 处理客户端数据 */
            	int client_fd = event_array[i].data.fd;
            	ssize_t bytes_read;
            	while ((bytes_read = read(client_fd, buf, sizeof(buf)-1)) > 0)
	    		{
                	buf[bytes_read] = '\0';
                	log_debug("Received %zd bytes from fd %d: %s", bytes_read, client_fd, buf);

           

                	if (db_insert(pack) < 0)
	       			{
                    		log_error("db_insert failed");
                	}
            	}
		printf("kao\n");

            	if (bytes_read == 0)
	    		{  /* 客户端关闭连接 */
                	log_info("Client fd %d disconnected", client_fd);
                	close(client_fd);
            	}
	    		else if (bytes_read < 0 && errno != EAGAIN)
	    		{
                	log_error("read from fd %d failed: %s", client_fd, strerror(errno));
                	close(client_fd);
            	}
        }
    }
			printf("fuck\n");
    		printf("DEBUG: Port before init=%d\n", serv_port); // 放在socket_server_init前
    
   /*  if (serv_port == 0)
    { // 如果端口仍未设置
    	fprintf(stderr, "Error: Port must be specified with -p\n");
    	print_usage(progname);
    	return EXIT_FAILURE;
    }*/


CleanUp:
    /* 资源清理 */
    log_info("Server shutting down...");
    if (epoll_rv >= 0) close(epoll_rv);
    if (listen_fd >= 0) close(listen_fd);
    if (pack)
    {
        free(pack);
        pack = NULL;
    }
    log_close();
    return 0;

}

void signal_handler(int sig)
{
     log_info("Server shutdown by signal %d", sig);  // 实际使用参数
}

int print_usage(char *progname)
{
	printf("%s usage:\n",progname);
    printf("-p(--port) input the port you will bind\n");
    printf("-d(--daemon) the program will run at background\n");
    printf("-h(--help) print the help massage\n");
	printf("\nExample: %s -b -p 8900\n", progname);
	return 0;

}

int socket_server_init(char *listen_ip, int listen_port)
{
	
	struct sockaddr_in servaddr;
	int rv = 0;
	int on = 1;
	int listen_fd;
	if ( (listen_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		printf("Use socket() to create a TCP socket failure: %s\n", strerror(errno));
		return -1;
	}
	/*  Set socket port reuseable, fix 'Address already in use' bug when socket server restart */
	setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(listen_port);
	if( !listen_ip ) /*  Listen all the local IP address */
	{
		servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	}
	else /*  listen the specified IP address */
	{
		if  (inet_pton(AF_INET, listen_ip, &servaddr.sin_addr) <= 0 )
		{
			printf("inet_pton() set listen IP address failure.\n");
			rv = -2;
			goto CleanUp;
		}
	}
	if( bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 )
	{
		printf("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
		rv = -3;
		goto CleanUp;
	}
	if( listen(listen_fd, 64) < 0)
	{
		printf("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
		rv = -4;
		goto CleanUp;
	}
CleanUp:
	if( rv<0 )
		close(listen_fd);
	else
		rv = listen_fd;
	return rv;
}

/*  Set open file description count to max */
int set_socket_rlimit(void)
{
	struct rlimit limit = {0};
	getrlimit(RLIMIT_NOFILE, &limit );
	limit.rlim_cur = limit.rlim_max;
	setrlimit(RLIMIT_NOFILE, &limit );
	printf("set socket open fd max count to %ld\n", limit.rlim_max);
	return 0;
}

